/*
 * @Author: meifeng mei.feng@asiainfo-sec.com
 * @Date: 2023-10-18 10:10:15
 * @LastEditors: meifeng mei.feng@asiainfo-sec.com
 * @LastEditTime: 2024-04-28 12:50:39
 * @FilePath: \admin_vue\src\express\express_app\routes\runScript.js
 * @Description:
 *
 * Copyright (c) 2023 by ${meifeng}, All Rights Reserved.
 */
let express = require('express')
const fs = require('fs')
const path = require('path')
const { exec } = require('child_process')


const getImagesInFolder = (folderPath) => {
    try {
        const files = fs.readdirSync(folderPath)
        const imageNames = files.filter(file => file.endsWith('.jpg') || file.endsWith('.png')) // 这里假设您只需要 jpg 和 png 格式的图片
        return imageNames
    } catch (error) {
        console.error(error)
        return []
    }
}

let router = express.Router()

router.get('/', (req, res, next) => {
    const scriptPath = path.join(__dirname, '..', 'py', 'mix.py') // 这里将相对路径转换为绝对路径
    const command = `python ${scriptPath} --area=${req.query.area} --page=${req.query.page}`
    exec(command, (error, stdout, stderr) => {
        if (error) {
            console.error(`执行本地脚本时发生错误：${error.message}`)
            return res.status(500).send(`执行本地脚本时发生错误：${error.message}`)
        }
        if (stderr) {
            console.error(`本地脚本执行过程中有错误：${stderr}`)
            return res.status(500).send(`本地脚本执行过程中有错误：${stderr}`)
        }
        console.log(`执行结果：${stdout}`)
        res.send('执行结果：成功')
    })
})

// 获取指定文件夹下所有图片文件的文件名并转换为 base64
function getBase64ImagesInFolder(folderPath) {
    const fileNames = fs.readdirSync(folderPath)
    const imageFileNames = fileNames.filter(fileName => {
        const ext = path.extname(fileName).toLowerCase()
        return ext === '.png' || ext === '.jpg' || ext === '.jpeg'
    })

    const base64Images = imageFileNames.map(fileName => {
        const filePath = path.join(folderPath, fileName)
        const fileData = fs.readFileSync(filePath)
        const base64Data = Buffer.from(fileData).toString('base64')
        const mimeType = path.extname(fileName).toLowerCase() === '.jpg' ? 'image/jpeg' : 'image/png'
        return `data:${mimeType};base64,${base64Data}`
    })

    return base64Images
}

router.get('/images', (req, res) => {
    const folderPath = req.query.folderPath // 获取查询参数中的文件夹路径
    if (!folderPath) {
        return res.status(400).send('文件夹路径不能为空')
    }

    // 检查文件夹是否存在
    if (!fs.existsSync(folderPath)) {
        return res.status(404).send('指定的文件夹不存在')
    }

    try {
        // 获取base64格式的图片数组
        // const base64Images = getBase64ImagesInFolder(folderPath)
        // res.send(base64Images)
        // 获取图片名字
        const imageNames = getImagesInFolder(folderPath)
        res.send(imageNames)
    } catch (error) {
        console.error(`获取图片时发生错误：${error.message}`)
        res.status(500).send(`获取图片时发生错误：${error.message}`)
    }
})

module.exports = router